#!/bin/bash
source $DRAW_INI
source $DRAW_CFG

DFILE="../csv/s_${1}${2}.recal_data.csv"
if [ ! -s "$DFILE" ]; then
 echo "Error: missing recalfile $DFILE"
 exit 100
fi

rm core.* 2> /dev/null


# By Chr if BAM > 10GB
if [ $(stat --printf="%s" "s_${1}${2}.bam") -gt 10024000000 ];then

  CHR="chr"$SGE_TASK_ID

  if [ $SGE_TASK_ID -eq 23 ]; then CHR="chrX";fi;
  if [ $SGE_TASK_ID -eq 24 ]; then CHR="chrY";fi;

  java -Xmx2800m -jar $GATK \
   -l INFO \
   -R $REF_FASTA \
   -et NO_ET \
   -I s_${1}${2}.bam \
   -L $CHR \
   -T TableRecalibration \
    -o s_${1}${2}_recal.$CHR.bam \
    --disable_bam_indexing \
    -recalFile "$DFILE"
else #BAM <=10GB

 if [ $SGE_TASK_ID -gt 1 ];then exit 0;fi;

 CHR=FULL
 java -Xmx2800m -jar $GATK \
   -l INFO \
   -R $REF_FASTA \
   -et NO_ET \
   -I s_${1}${2}.bam \
   -T TableRecalibration \
    -o s_${1}${2}_recal.FULL.bam \
    -recalFile "$DFILE"

fi #eof by chr

# throw error if < 1024 bytes
if [ $(stat --printf="%s" "s_${1}${2}_recal.$CHR.bam") -le 1024 ]
then
    exit 100

fi

# Check for core dumps (errors) from bwa
CORE_LIST=$(ls core.*)
if [ -n "$CORE_LIST" ]
  then
   echo "Found core dumps. Exiting with error."
   exit 100
fi
